package com.qfoud.edu.shiro.framwork.slot.impl;

import com.qfoud.edu.shiro.framwork.exception.ShiroException;
import com.qfoud.edu.shiro.framwork.slot.base.BaseSlot;
import com.qfoud.edu.shiro.framwork.utils.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author xiaobobo
 * @title: AuthorizeSlot
 * @projectName cd-java-2303-project-parent
 * @description: 授权的这个slot
 * @date 2023/5/15  15:06
 */
public class AuthorizeSlot implements BaseSlot {

    //登陆页面
    private String loginPage;

    private String loginUrl;

    public AuthorizeSlot(String loginPage, String loginUrl){
        this.loginPage=loginPage;
        this.loginUrl=loginUrl;
    }


    @Override
    public void dealRequestAndResponse(ServletRequest request, ServletResponse response) throws IOException {
        System.out.println("授权的slot也执行了....");
        //这里就知道了登陆页面是谁了....
        //这里如果是有标记那么说明就登陆了 没标记 那么就说明未登录
        HttpServletRequest req= (HttpServletRequest) request;
        //获取请求地址
        String requestURI = req.getRequestURI();
        if(StringUtils.equals(requestURI,loginUrl)){
            System.out.println("说明是登陆的控制器请求");
            return ;
        }

        if(StringUtils.equals(requestURI,loginPage)){
            System.out.println("说明是登陆的页面");
            return ;
        }
        //获取响应对象
        HttpServletResponse resp= (HttpServletResponse) response;

        HttpSession session = req.getSession();
        String strTag = (String) session.getAttribute("user");
        if(StringUtils.isEmpty(strTag)){
            //说明用户未登录
            //未登录 就要跳转到 登陆页面
            resp.sendRedirect(loginPage);
            throw new ShiroException("用户未登录执行到登陆页面");
        }
    }
}
